/*
 * Copyright 2006-2009 Matthieu Chase Heimer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
package com.macro10.xroads.xml;

import com.macro10.util.FileUtils;
import com.macro10.xroads.xml.generated.XMLElement;
import com.macro10.xroads.xml.generated.XMLElementCollection;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;

public class ElementParser {

    private static final Logger logger = Logger.getLogger(ElementParser.class.getPackage().getName());
    private static String xmlDir = System.getProperty("ElementDir", "src");
    private static String xmlFile = System.getProperty("ElementFile", "elements.xml");
    private static ElementParser instance;
    private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(true);
    private final Lock r = rwl.readLock();
    private final Lock w = rwl.writeLock();
    private Map<String, XMLElement> elements;

    private ElementParser() throws Exception {
        logger.log(Level.INFO, "Loaded " + getClass().getName());
        loadElements();
    }

    public static ElementParser loadInstance() throws Exception {
        if (instance == null) {
            instance = new ElementParser();
        }
        return instance;
    }

    public static ElementParser getInstance() {
        return instance;
    }

    public void loadElements() throws Exception {
        w.lock();
        elements = new HashMap<String, XMLElement>();

        JAXBContext jc = null;
        Unmarshaller u = null;

        try {
            jc = JAXBContext.newInstance("com.macro10.xroads.xml.generated");
            u = jc.createUnmarshaller();
        } catch (JAXBException ex) {
            logger.log(Level.ERROR, "Error creating JAXB context for XMLElementParser", ex);
            w.unlock();
            throw ex;
        }

        logger.log(Level.INFO, "Searching for element xml files underneath: " + new File(xmlDir).getAbsolutePath());
        File[] xmlFiles = FileUtils.getAllFilesUnderByName(new File(xmlDir), xmlFile);
        logger.log(Level.INFO, "Found " + xmlFiles.length + " element xml file(s)");
        for (File elementFile : xmlFiles) {
            logger.log(Level.INFO, "Parsing element xml file: " + elementFile.getName());
            try {
                XMLElementCollection elementCollection = (XMLElementCollection) u.unmarshal(elementFile);

                List<XMLElement> elementList = elementCollection.getElements();
                for (XMLElement element : elementList) {
                    String elementName = element.getName();
                    if (elements.containsKey(elementName)) {
                        logger.log(Level.WARN, "Replacing duplicate element: " + elementName);
                    }
                    elements.put(elementName, element);
                }
            } catch (JAXBException ex) {
                logger.log(Level.ERROR, "Error parsing xml element file: " + elementFile.getName(), ex);
                w.unlock();
                throw ex;
            }
        }

        w.unlock();
    }

    public XMLElement getElement(String elementName) {
        r.lock();
        XMLElement element = elements.get(elementName);
        r.unlock();
        return element;
    }

    public Map<String, XMLElement> getElements() {
        r.lock();
        Map<String, XMLElement> localElements = this.elements;
        r.unlock();
        return localElements;
    }
}
